/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package opensocial.apps.common.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import opensocial.apps.common.AppContext;

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.configuration.Configuration;

public abstract class BaseCommand implements Command {
  protected static final boolean NEXT = false;
  protected static final boolean END = true;

  protected AppContext context;
  protected Configuration config;
  protected HttpServletRequest request;
  protected HttpServletResponse response;

  protected ResponseItem out;

  public AppContext getContext() {
    return context;
  }

  public boolean pre(Context context) {
    this.context = (AppContext) context;
    this.config = this.context.getConfiguration();
    this.request = this.context.getRequest();
    this.response = this.context.getResponse();
    this.out = new ResponseItem();

    this.context.put(AppContext.OUTPUT_KEY, out.getData());

    return NEXT;
  }

  public boolean execute(Context context) throws Exception {
    if (pre(context) == NEXT) {
      return execute();
    } else {
      return END;
    }
  }

  public abstract boolean execute() throws Exception;

  protected void output(Object out) {
    this.out.set("data",out);
  }
  
  protected void output(String key,Object value){
      this.out.set(key, value);
  }

  protected void hasError(boolean flag) {
    this.out.setHasError(flag);
  }
}
